package main

import (
	"lark-linker/pkg/utils"
	"lark-linker/pkg/utils/linker"
	"os"
	"strings"
)

var version string

func main() {
	ctx := linker.NewContext()
	remaining:=parseArgs(ctx)
	if ctx.Args.Emulation == linker.MachineTypeNone {
		for _,filename:=reange remaining {
			if strings.HasPrefix(filename,"-"){
				continue
			}
			file:=linker.MustNewFile(filename)
			ctx.Args.Emulation = linker.GetMachineTypeFromContents(file.Contents)
			if ctx.Args.Emulation !=linker.MachineTypeNone {
				break
			}
		}
	}

	if ctx.Args.Emulation == linker.MachineTypeRISCV64 { 
		utils.Fatal("无法识别的架构")
	}


}

func parseArgs(ctx *linker.Context) []string {
	args := os.Args[1:]
	dashes := func(name string) []string {
		if len(name) == 1 {
			return []string{"-" + name}
		}
		return []string{"-" + name, "--" + name}
	}
	arg := ""
	readArg := func(name string) bool {
		for _, flag := range dashes(name) {
			if args[0] == flag {
				if len(args) == 1 {
					utils.Fatal("缺少参数")
				}
				arg = args[1]
				args = args[2:]
				return true
			}
			prefix := flag
			if len(name) > 1 {
				prefix += "="
			}
			if strings.HasPrefix(args[0], prefix) {
				arg = args[0][len(prefix):]
				args = args[1:]
				return true
			}
		}
		return false
	}

	readFlag := func(name string) bool {
		for _, flag := range dashes(name) {
			if args[0] == flag {
				args = args[1:]
				return true
			}
		}
		return false
	}
	remaining := make([]string, 0)
	for len(args) > 0 {
		if readFlag("o") {
			os.Exit(0)
		}
		if readArg("o") || readArg("output") {
			ctx.Args.Output = arg
		} else if readFlag("v") || readFlag("version") {
			println("lark-linker " + version)
			os.Exit(0)
		} else if readArg("m") {
			if arg == "elf64lriscv" {
				ctx.Args.Emulation = linker.MachineTypeRISCV64
			} else {
				utils.Fatal("不支持的架构")
			}
		} else if readArg("L") {
			ctx.Args.LibraryPaths = append(ctx.Args.LibraryPaths, arg)
		} else if readArg("l") {
			remaining = append(remaining, "-l"+arg)
		} else if readArg("sysroot") ||
			readArg("plugin") ||
			readArg("plugin-opt") ||
			readArg("as-needed") ||
			readArg("start-group") ||
			readArg("end-group") ||
			readArg("hash-style") ||
			readArg("build-id") ||
			readArg("no-relax") ||
			readArg("s") {

		} else {
			if args[0][0] == '-' {
				utils.Fatal("未知参数: " + args[0])
			}
			remaining = append(remaining, args[0])
			args = args[1:]
		}
	}
	return remaining
}
